<template>
  <div>
    <el-row>

      <el-form class="search ml10" :inline="true" label-suffix="：" size="mini">
        <el-form-item>
          <el-button-group>
            <template v-for="(value, type) in paperTypes">
              <el-button
                :key="type"
                size="mini"
                :type="curPaper.type === type ? 'primary' : 'info'"
                @click="setPaper(type, value)"
              >
                {{ type }}</el-button>
            </template>
          </el-button-group>
        </el-form-item>
        <el-form-item label="宽度">
          <el-input v-model="width" type="number" class="w100" placeholder="请输入宽度" @change="WHChange" />
        </el-form-item>
        <el-form-item label="高度">
          <el-input v-model="height" type="number" class="w100" placeholder="请输入高度" @change="WHChange" />
        </el-form-item>
        <el-form-item>
          <el-button size="mini" type="primary" @click="preView">预览</el-button>
          <el-button size="mini" type="primary" @click="print">直接打印</el-button>
          <el-button size="mini" type="primary" @click="clearPaper">清空</el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <br>
    <el-row>
      <el-col :span="4">
        <el-card style="height: 100%">
          <el-row>
            <el-col :span="24" class="rect-printElement-types hiprintEpContainer">
              <el-row class="drag_item_title">基础元素</el-row>

              <el-row style="height: 100px">
                <el-col :span="12" class="drag_item_box">
                  <div>
                    <a class="ep-draggable-item" tid="defaultModule.text" style>
                      <span class="glyphicon glyphicon-text-width" aria-hidden="true" />
                      <p class="glyphicon-class">文本</p>
                    </a>
                  </div>
                </el-col>
                <el-col :span="12" class="drag_item_box">
                  <div>
                    <a class="ep-draggable-item" tid="defaultModule.longText" style>
                      <span class="glyphicon glyphicon-subscript" aria-hidden="true" />
                      <p class="glyphicon-class">长文</p>
                    </a>
                  </div>
                </el-col>
                <!-- <el-col :span="12" class="drag_item_box">
                  <div>
                    <a class="ep-draggable-item" tid="defaultModule.image" style>
                      <span class="glyphicon glyphicon-picture" aria-hidden="true" />
                      <p class="glyphicon-class">图片</p>
                    </a>
                  </div>
                </el-col> -->
              </el-row>

              <el-row style="height: 100px">

                <el-col :span="12" class="drag_item_box" tid="defaultModule.text">
                  <div>
                    <a class="ep-draggable-item" tid="defaultModule.table" style>
                      <span class="glyphicon glyphicon-th" aria-hidden="true" />
                      <p class="glyphicon-class">表格</p>
                    </a>
                  </div>
                </el-col>
              </el-row>

              <el-row class="drag_item_title">辅助</el-row>
              <el-row style="height: 100px">
                <el-col :span="12" class="drag_item_box">
                  <div>
                    <a class="ep-draggable-item" tid="defaultModule.hline" style>
                      <span class="glyphicon glyphicon-resize-horizontal" aria-hidden="true" />
                      <p class="glyphicon-class">横线</p>
                    </a>
                  </div>
                </el-col>

                <el-col :span="12" class="drag_item_box">
                  <div>
                    <a class="ep-draggable-item" tid="defaultModule.vline" style>
                      <span class="glyphicon glyphicon-resize-vertical" aria-hidden="true" />
                      <p class="glyphicon-class">竖线</p>
                    </a>
                  </div>
                </el-col>
              </el-row>

              <el-row style="height: 100px;">
                <el-col :span="12" class="drag_item_box" tid="defaultModule.text">
                  <div>
                    <a class="ep-draggable-item" tid="defaultModule.rect">
                      <span class="glyphicon glyphicon-unchecked" aria-hidden="true" />
                      <p class="glyphicon-class">矩形</p>
                    </a>
                  </div>
                </el-col>
                <el-col :span="12" class="drag_item_box" tid="defaultModule.text">
                  <div>
                    <a class="ep-draggable-item" tid="defaultModule.oval">
                      <span class="glyphicon glyphicon-record" aria-hidden="true" />
                      <p class="glyphicon-class">椭圆</p>
                    </a>
                  </div>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-card>
      </el-col>

      <el-col :span="15">
        <el-card class="card-design">
          <div id="hiprint-printTemplate" class="hiprint-printTemplate" />
        </el-card>
      </el-col>

      <el-col :span="5">
        <el-card>
          <el-row class="hinnn-layout-sider">
            <div id="PrintElementOptionSetting" />
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    <!-- <div v-if="showBtn" class="footer">
      <el-button type="primary" size="small" @click="preserveFormwork()">保 存</el-button>
    </div> -->
    <print-preview ref="preView" />
  </div>
</template>

<script>
import { hiprint, defaultElementTypeProvider } from 'vue-plugin-hiprint';
import panel from './common/panel';
import printData from './common/print-data';
import printPreview from './common/preview';

let hiprintTemplate;

export default {
  name: 'Print',
  components: {
    printPreview
  },
  props: {
    nameType: {
      type: String,
      default() {
        return '';
      }
    },
    jsonMain: {
      type: String,
      default: ''
    }
  },

  data() {
    return {
      curPaper: {
        type: 'A4',
        width: 210,
        height: 296.6
      },
      paperTypes: {
        A3: {
          width: 420,
          height: 296.6
        },
        A4: {
          width: 210,
          height: 296.6
        },
        A5: {
          width: 210,
          height: 147.6
        },
        B3: {
          width: 500,
          height: 352.6
        },
        B4: {
          width: 250,
          height: 352.6
        },
        B5: {
          width: 250,
          height: 175.6
        }
      },
      scaleValue: 1,
      scaleMax: 5,
      scaleMin: 0.5,
      showBtn: true,
      panelData: {},
      width: '',
      height: ''
    };
  },
  watch: {
    myJSON(newVal) {
      // this.initHiprintTemplate(JSON.parse(newVal).panels);
    }
  },
  mounted() {
    this.panelData = panel;
    // console.log(this.nameType);
    if (this.nameType == '新增') {
      this.initHiprintTemplate();
    } else if (this.nameType == '打印') {
      this.panelData = JSON.parse(this.jsonMain);
      // console.log('-------' + this.panelData);
      this.initHiprintTemplate('打印');
    }
  },
  methods: {
    initData(a) {
      if (hiprintTemplate) {
        hiprintTemplate.clear();
      }
      this.panelData = JSON.parse(a);
      // console.log('-------' + this.panelData);
      this.initHiprintTemplate();
    },
    initHiprintTemplate(type) {
      let that = this;
      hiprint.init({
        providers: [defaultElementTypeProvider()]
      });
      // 还原配置
      hiprint.setConfig();
      // 替换配置
      hiprint.setConfig({
        movingDistance: 2.5,
        text: {
          supportOptions: [
            {
              name: 'styler',
              hidden: true
            },
            {
              name: 'formatter',
              hidden: true
            }
          ]
        }
      });
      // eslint-disable-next-line no-undef
      hiprint.PrintElementTypeManager.buildByHtml($('.ep-draggable-item'));
      hiprintTemplate = new hiprint.PrintTemplate({
        template: that.panelData,
        settingContainer: '#PrintElementOptionSetting',
        paginationContainer: '.hiprint-printPagination'
      });
      hiprintTemplate.design('#hiprint-printTemplate');
      // console.log(hiprintTemplate);
      // 获取当前放大比例, 当zoom时传true 才会有
      this.scaleValue = hiprintTemplate.editingPanel.scale || 1;
      if (this.type == '打印') {
        this.preView();
      }
    },
    setPaper(type, value) {
      try {
        if (Object.keys(this.paperTypes).includes(type)) {
          this.curPaper = {
            type: type,
            width: value.width,
            height: value.height
          };
          hiprintTemplate.setPaper(value.width, value.height);
        } else {
          this.curPaper = {
            type: 'other',
            width: value.width,
            height: value.height
          };
          hiprintTemplate.setPaper(value.width, value.height);
        }
      } catch (error) {
        this.$message.error(`操作失败: ${error}`);
      }
    },

    changeScale(big) {
      let scaleValue = this.scaleValue;
      if (big) {
        scaleValue += 0.1;
        if (scaleValue > this.scaleMax) scaleValue = 5;
      } else {
        scaleValue -= 0.1;
        if (scaleValue < this.scaleMin) scaleValue = 0.5;
      }
      if (hiprintTemplate) {
        // scaleValue: 放大缩小值, false: 不保存(不传也一样), 如果传 true, 打印时也会放大
        hiprintTemplate.zoom(scaleValue);
        this.scaleValue = scaleValue;
      }
    },

    onlyPrint() {
      let hiprintTemplate = this.$print(
        undefined,
        panel,
        printData,
        {},
        {
          styleHandler: () => {
            let css =
              '<link href="http://hiprint.io/Content/hiprint/css/print-lock.css" media="print" rel="stylesheet">';
            return css;
          }
        }
      );
      console.log(hiprintTemplate);
    },

    onlyPrint2() {
      let that = this;
      if (window.hiwebSocket.opened) {
        let hiprintTemplate = this.$print2(undefined, panel, printData, {
          printer: '',
          title: 'Api单独打印',
          styleHandler: () => {
            let css =
              '<link href="http://hiprint.io/Content/hiprint/css/print-lock.css" media="print" rel="stylesheet">';
            return css;
          }
        });
        let key = 'Api单独直接打印';
        hiprintTemplate.on('printSuccess', function() {
          that.$notification.success({
            key: key,
            placement: 'topRight',
            message: key + ' 打印成功',
            description: 'Api单独直接打印回调'
          });
        });
        return;
      }
      this.$message.error('客户端未连接,无法直接打印');
    },
    preserveFormwork() {
      // this.showBtn = false;
      // this.$emit('onSubmit', hiprintTemplate.lastJson);
      return hiprintTemplate.lastJson;
    },
    preView() {
      console.log(hiprintTemplate, printData);
      this.$refs.preView.show(hiprintTemplate, printData);
    },

    print() {
      hiprintTemplate.print(printData, {
        printer: '',
        title: 'hiprint测试打印'
      });
      // if (window.hiwebSocket.opened) {
      //   const printerList = hiprintTemplate.getPrinterList();
      //   console.log(printerList);
      //   hiprintTemplate.print(printData, {
      //     printer: '',
      //     title: 'hiprint测试打印'
      //   });
      //   return;
      // }
      // this.$message.error('客户端未连接,无法直接打印');
    },

    clearPaper() {
      try {
        hiprintTemplate.clear();
      } catch (error) {
        this.$message.error(`操作失败: ${error}`);
      }
    },
    WHChange(value) {
      if (this.width && this.height && this.width > 0 && this.height > 0) {
        hiprintTemplate.setPaper(this.width, this.height);
        this.curPaper = {};
      } else if (!this.curPaper.type) {
        this.curPaper = {
          type: 'A4',
          width: 210,
          height: 296.6
        };
        hiprintTemplate.setPaper(210, 296.6);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.drag_item_box {
  height: 100%;
  padding: 6px;
}

.drag_item_box > div {
  height: 100%;
  width: 100%;
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
}

.drag_item_box > div > a {
  text-align: center;
  text-decoration-line: none;
}

.drag_item_box > div > a > span {
  font-size: 28px;
}

.drag_item_box > div > a > p {
  margin: 0;
}

.drag_item_title {
  font-size: 16px;
  padding: 12px 6px 0 6px;
  font-weight: bold;
}

// .hiprint-printElement-image-content {
//   img {
//     content: url("~@/assets/logo.png");
//   }
// }

.card-design {
  overflow: hidden;
  overflow-x: auto;
  overflow-y: auto;
}
.footer {
  position: absolute;
  right: 120px;
  bottom: 40px;
  z-index: 999;
}
</style>
